package com.yjz.middleware.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * @author :yuanJinZhong
 * @description:
 * @date :2018/11/27-11:28
 */
@Slf4j
public class StudentProtocolClientHandler extends ChannelDuplexHandler {
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) {

  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // 往服务端发送pojo
    ByteBuf writeByteBuf = ctx.alloc().buffer();
    Student student = Student.builder().age(27).name("划过天空阿忠").build();
    writeByteBuf.writeBytes(student.toString().getBytes(Charset.forName("Utf-8")));
    log.info("发往服务端个的实体为:{}", student.toString());
    ChannelFuture future0 = ctx.writeAndFlush(student);
    future0.addListener(new ChannelFutureListener() {
      @Override
      public void operationComplete(ChannelFuture future) throws Exception {
        if (future0 == future) {
          future.channel().close();
        }
      }
    });
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    ctx.close();
  }
}
